<?php

namespace App\Http\Controllers\Admin;

use App\Constant\Constant;
use App\Models\Label;
use App\Requests\Label\StoreRequest;
use Illuminate\Http\Request;
use App\Exceptions\ExceptionSms;
use Carbon\Carbon;
use App\Helpers\MoneyHelper;

/**
 * 标签管理
 * Class LabelController
 * @package App\Http\Controllers\Admin
 */
class LabelController extends CommonController
{
    protected $model = Label::class;

    public function index($list_type)
    {
        $search_forms                  = Label::getForms(['name', 'type']);
        $search_forms['type']['value'] = $list_type;

        $cols = [[
            ['field' => 'name', 'title' => '名称'],
            ['field' => 'icon_format', 'title' => '图标', 'escape' => false],
            ['field' => 'action', 'title' => '操作', 'templet' => '#list-bar'],
        ]];

        if ($list_type == Constant::LabelType_HotelPhoto) {
            unset($cols[0][1]);
        }

        $permission_code = "label-{$list_type}-query";

        $uri = '/admin/label/list?code=' . $permission_code . '&type=' . $list_type;

        $top_btns = [
            ['code' => "label-{$list_type}-add", 'params' => ['type' => $list_type]]
        ];

        $row_btns = [
            ['code' => "label-{$list_type}-edit"],
            ['code' => "label-{$list_type}-delete"]
        ];

        return view('components.list', compact('search_forms', 'cols', 'permission_code', 'uri', 'top_btns', 'row_btns'));
    }

    public function dataList()
    {
        $list = Label::bgBaseQuery($this->input())->paginate($this->limit);
        foreach ($list as $item) {
            $item->icon_format = $item->formatImage($item->icon);
        }
        return ExceptionSms::homeList($list->items(), $list->total());
    }

    public function editAdd()
    {
        $id   = $this->input('id') ?? 0;
        $type = $this->input('type');
        $data = $id ? Label::getOneById($id) : null;

        $save_forms = Label::getForms(['name', 'icon', 'type'], 'save');
        if ($data) {

            $save_forms['icon']['value'] = $data->icon;
            $type                        = $data->type;
        }
        $save_forms['type']['value'] = $type;
        if ($type != Constant::LabelType_HotelFacility) {
            unset($save_forms['icon']);
        }

        $permission_code = $id ? "label-{$type}-edit-save" : "label-{$type}-add-save";

        \Log::info($permission_code);
        return view('components.save_form', compact('data', 'save_forms', 'permission_code'));
    }

    public function dataSave(StoreRequest $request)
    {
        $id = $request->get('id') ?? "";
        if ($id) $data = Label::getOneById($id);
        else $data = new Label();
        $data->name = $request->get("name");
        $data->icon = $request->get("icon") ?? "";
        $data->type = $request->get("type");
        $data->save();
        return ExceptionSms::returnSuccess();
    }
}
